<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据日期" prop="documentDate">
        <el-date-picker clearable v-model="queryParams.documentDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="核销金额" prop="reconciliationAmount">
        <el-input v-model="queryParams.reconciliationAmount" placeholder="请输入核销金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单据阶段" prop="documentStage">
        <el-input v-model="queryParams.documentStage" placeholder="请输入单据阶段" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="生效时间" prop="effectiveTime">
        <el-date-picker clearable v-model="queryParams.effectiveTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择生效时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批人" prop="approver">
        <el-input v-model="queryParams.approver" placeholder="请输入审批人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="制单人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入制单人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="修改人" prop="modifyBy">
        <el-input v-model="queryParams.modifyBy" placeholder="请输入修改人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker v-model="daterangeModifyTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="核批意见" prop="approvalRemark">
        <el-input v-model="queryParams.approvalRemark" placeholder="请输入核批意见" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单据编号" prop="documentCode">
        <el-input v-model="queryParams.documentCode" placeholder="请输入单据编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['finance:receiveReconciliation:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['finance:receiveReconciliation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['finance:receiveReconciliation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['finance:receiveReconciliation:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiveReconciliationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" fixed="left"  align="center" prop="documentCode" width="180">
        <template slot-scope="scope">
          <span style="color: #46a6ff;" @click="handleDetail(scope.row.id)">{{ scope.row.documentCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据日期" align="center" prop="documentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.documentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="cusName" width="120" />
      <el-table-column label="核销金额" align="center" prop="reconciliationAmount" width="120" />
      <el-table-column label="单据阶段" align="center" prop="documentStage" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.documentStage === 1" style="color: orange;">已完成</span>
          <span v-else-if="scope.row.documentStage === 0" style="color: green;">编制中</span>
        </template>
      </el-table-column>
      <el-table-column label="核批状态" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.approvalResult === 1" style="color: orange;">待审核</span>
          <span v-else-if="scope.row.approvalResult === 2" style="color: green;">审核通过</span>
          <span v-else-if="scope.row.approvalResult === 3" style="color: red;">驳回</span>
        </template>
      </el-table-column>
      <el-table-column label="是否生效" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isEffect === 1" style="color: red;">是</span>
          <span v-else-if="scope.row.isEffect === 0" style="color: green;">否</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isClose === 1" style="color: red;">是</span>
          <span v-else-if="scope.row.isClose === 0" style="color: green;">否</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isCancel === 1" style="color: red;">是</span>
          <span v-else-if="scope.row.isCancel === 0" style="color: green;">否</span>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approver" />
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="核批意见" align="center" prop="approvalRemark" width="320" />
      <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-s-data" @click="shenhe(scope.row.id)"
            :disabled="scope.row.approvalResult !== 1">
            审核
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['finance:receiveReconciliation:edit']"  :disabled="scope.row.approvalResult !== 1">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['finance:receiveReconciliation:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改应收核销单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="formRecive" :rules="rules" inline label-width="80px">
        <el-form-item label="单据日期" prop="documentDate">
          <el-date-picker clearable v-model="formRecive.documentDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户" prop="cusId">
          <el-select v-model="formRecive.cusId" placeholder="请选择" @change="cusSelectChanged" :disabled="isEdit">
            <el-option v-for="item in cusList" :key="item.id" :label="item.cusName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据编号" prop="documentCode">
          <el-input v-model="formRecive.documentCode" disabled placeholder="请输入单据编号" />
        </el-form-item>
        <el-form-item label="核销金额" prop="reconciliationAmount">
          <el-input v-model="formRecive.reconciliationAmount" disabled placeholder="请输入核销金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formRecive.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <!-- 左侧 -->
        <el-col :span="12">
          <div>
            <!-- 应收单 -->
            <h3>应收单</h3>
            <el-table ref="reciveTable" :data="reciveList" style="width: 100%"
              @selection-change="handleSelectionChangeRecive">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="orderCode" label="单据号" width="150">

              </el-table-column>
              <el-table-column prop="srcOrderCode" label="源单号" width="150"></el-table-column>
              <el-table-column label="未核销金额" width="150">
                <template slot-scope="scope">
                  <span>{{ scope.row.money - scope.row.verMoney }}元</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="150"></el-table-column>
            </el-table>
            <el-button size="small" type="primary" @click="addMustRecive">添加</el-button>
            <pagination v-show="reciveReq.total > 0" :total="reciveReq.total" :page.sync="reciveReq.pageNum"
              :limit.sync="reciveReq.pageSize" :page-sizes="[5, 10, 20, 30, 50]" @pagination="getReciveList">
            </pagination>
          </div>

          <div style="margin-top: 20px;">
            <!-- 收款单 -->
            <h3>收款单</h3>
            <el-table ref="reciveOrderTable" :data="reciveOrderList" style="width: 100%"
              @selection-change="handleSelectionChangeReciveOrder">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="orderCode" label="单据号" width="150"></el-table-column>
              <el-table-column prop="paymentTypeName" label="收款类型" width="150"></el-table-column>
              <el-table-column label="未核销金额" width="150">
                <template slot-scope="scope">
                  <span>{{ scope.row.money - scope.row.verMoney }}元</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="150"></el-table-column>
            </el-table>
            <el-button size="small" type="primary" @click="addRecive">添加</el-button>
            <pagination v-show="reciveOrder.total > 0" :total="reciveOrder.total" :page.sync="reciveOrder.pageNum"
              :limit.sync="reciveOrder.pageSize" :page-sizes="[5, 10, 20, 30, 50]" @pagination="getReciveOrderList">
            </pagination>
          </div>
        </el-col>

        <!-- 右侧 -->
        <el-col :span="12">
          <div>
            <!-- 核销明细-应收 -->
            <h3>核销明细-应收</h3>
            <el-table :data="reciveDetailList" style="width: 100%"
              @selection-change="handleSelectionChangeReciveDetail">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="sourceDocumentNo" label="源单号" width="150"></el-table-column>
              <el-table-column prop="typeName" label="源单类型" width="150"></el-table-column>
              <el-table-column prop="reqAmount" label="未核销金额" width="150"></el-table-column>
              <el-table-column prop="reconciliationAmount" label="核销金额" width="150">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.reconciliationAmount" @change="changeAmount()" placeholder="请输入金额"
                    size="small"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-button size="small" @click="delMustPay">移除</el-button>
            <p>合计: <span>{{ mustReciveAll }}</span></p>
          </div>

          <div style="margin-top: 20px;">
            <!-- 核销明细-收款 -->
            <h3>核销明细-收款</h3>
            <el-table :data="reciveOrderDetailList" style="width: 100%"
              @selection-change="handleSelectionChangeReciveOrderDetail">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="sourceDocumentNo" label="源单号" width="150"></el-table-column>
              <el-table-column prop="typeName" label="源单类型" width="150"></el-table-column>
              <el-table-column prop="orderAmount" label="未核销金额" width="150"></el-table-column>
              <el-table-column prop="reconciliationAmount" label="核销金额" width="150">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.reconciliationAmount" @change="updateReciveAll()"
                    placeholder="请输入金额" size="small"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-button size="small" @click="delRecive">移除</el-button>
            <p>合计: <span>{{ reciveAll }}</span></p>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="核销明细" :visible.sync="view" width="80%" append-to-body>
      <template>
        <div>
          <el-descriptions>
            <el-descriptions-item label="单据编号" content-class-name="my-content">{{
              receiveReconciliation.documentCode
            }}</el-descriptions-item>
            <el-descriptions-item label="单据日期">{{
              receiveReconciliation.documentDate
            }}</el-descriptions-item>
            <el-descriptions-item label="客户">{{
              receiveReconciliation.cusName
            }}</el-descriptions-item>
            <el-descriptions-item label="核销金额">{{
              receiveReconciliation.reconciliationAmount
            }}元</el-descriptions-item>
            <el-descriptions-item label="业务员">{{
              receiveReconciliation.createBy
            }}</el-descriptions-item>
            <el-descriptions-item label="制单时间">{{
              receiveReconciliation.createTime
            }}</el-descriptions-item>
            <el-descriptions-item label="单据阶段">
            <span v-if="receiveReconciliation.documentStage === 1" style="color: orange;">已完成</span>
            <span v-else-if="receiveReconciliation.documentStage === 0" style="color: green;">编制中</span>
          </el-descriptions-item>
            <el-descriptions-item label="核批状态">
              <span v-if="receiveReconciliation.approvalResult === 1" style="color: orange;">待审核</span>
              <span v-else-if="receiveReconciliation.approvalResult === 2" style="color: green;">审核通过</span>
              <span v-else-if="receiveReconciliation.approvalResult === 3" style="color: red;">驳回</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-row>
          <el-col :span="12">
            <div>
              <!-- 核销明细-应收 -->
              <h3>核销明细-应收</h3>
              <el-table :data="reqViewDetailReciveOrder" style="width: 100%">
                <el-table-column prop="sourceDocumentNo" label="源单号" width="150"></el-table-column>
                <el-table-column prop="typeName" label="源单类型" width="150"></el-table-column>
                <el-table-column prop="reqAmount" label="未核销金额" width="150"></el-table-column>
                <el-table-column prop="reconciliationAmount" label="核销金额" width="150">
                </el-table-column>
              </el-table>
              <p>合计: <span>{{ receiveReconciliation.reconciliationAmount }}</span></p>
            </div>
            <div style="margin-top: 20px;">
              <!-- 核销明细-收款 -->
              <h3>核销明细-收款</h3>
              <el-table :data="reqViewDetailRecive" style="width: 100%">
                <el-table-column prop="sourceDocumentNo" label="源单号" width="150"></el-table-column>
                <el-table-column prop="typeName" label="源单类型" width="150"></el-table-column>
                <el-table-column prop="orderAmount" label="未核销金额" width="150"></el-table-column>
                <el-table-column prop="reconciliationAmount" label="核销金额" width="150">
                </el-table-column>
              </el-table>
              <p>合计: <span>{{ receiveReconciliation.reconciliationAmount }}</span></p>
            </div>
          </el-col>
        </el-row>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="reviewDialogVisible" width="40%">
      <el-descriptions title="单据基本信息" :column="2" border>
        <el-descriptions-item label="单据编号" content-class-name="my-content">
          {{ shenheData.documentCode }}
        </el-descriptions-item>
        <el-descriptions-item label="单据日期">
          {{ parseTime(shenheData.documentDate, '{y}-{m}-{d}') }}
        </el-descriptions-item>
        <el-descriptions-item label="客户">
          {{ shenheData.cusName }}
        </el-descriptions-item>
        <el-descriptions-item label="核销金额">
          {{ shenheData.reconciliationAmount }}元
        </el-descriptions-item>
        <el-descriptions-item label="业务员">
          {{ shenheData.createBy }}
        </el-descriptions-item>
        <el-descriptions-item label="制单时间">
          {{ parseTime(shenheData.createTime, '{y}-{m}-{d}') }}
        </el-descriptions-item>
        <el-descriptions-item label="单据阶段">
          <span v-if="shenheData.documentStage === 1" style="color: orange;">已完成</span>
          <span v-else-if="shenheData.documentStage === 0" style="color: green;">编制中</span>
        </el-descriptions-item>
        <el-descriptions-item label="核批状态">
          <span v-if="shenheData.approvalResult === 1" style="color: orange;">待审核</span>
          <span v-else-if="shenheData.approvalResult === 2" style="color: green;">审核通过</span>
          <span v-else-if="shenheData.approvalResult === 3" style="color: red;">驳回</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-form label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewResult" v-removeAriaHidden>
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input type="textarea" v-model="reviewRemark" placeholder="请输入审核意见" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReview">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listReceiveReconciliation, getReciveOrderList, getAllCus, getReciveList, getReceiveReconciliation, delReceiveReconciliation, addReceiveReconciliation, updateReceiveReconciliation, approval } from "@/api/finance/receiveReconciliation";
export default {
  name: "ReceiveReconciliation",
  data() {
    return {
      approvalDto: {
        approvalResult: 0,
        approvalRemark: '',
        id: 0,
      },
      reviewDialogVisible: false, // 审核弹框的显示与隐藏
      reviewResult: '', // 审核结果（通过或驳回）
      reviewRemark: '',// 审核意见
      currentReviewId: 0, //审核时的核销单id
      //是否可选客户
      isEdit: false,
      // 弹出层
      view: false,
      //储存选中的收款单详情
      selectedReciveOrderDetails: [],
      //储存选中的应付单详情
      selectedReciveDetails: [],
      // 存储选中的应收单
      selectedRecives: [],
      // 存储选中的收款单           
      selectedReciveOrders: [],

      //明细列表
      reciveDetailList: [],
      reciveOrderDetailList: [],
      //核销明细
      reconciliationDetailList: [],
      //客户列表
      cusList: [],
      //根据客户查询出来的应收列表
      reciveList: [],
      //根据客户查询出来的收款单列表
      reciveOrderList: [],
      reciveAll: 0,
      mustReciveAll: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应收核销单表格数据
      receiveReconciliationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 单据编号时间范围
      daterangeModifyTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentDate: null,
        reconciliationAmount: null,
        documentStage: null,
        effectiveTime: null,
        approver: null,
        createBy: null,
        modifyBy: null,
        modifyTime: null,
        approvalRemark: null,
        documentCode: null
      },
      reciveReq: {
        pageNum: 1,
        pageSize: 5,
        customerId: 0,
        orderStatus: 3,
        total: 0,
      },
      reciveOrder: {
        pageNum: 1,
        pageSize: 5,
        customerId: 0,
        orderStatus: 3,
        total: 0,
      },
      // 表单参数
      form: {},
      formRecive: {
        receiveReconciliationDetailList: [],
      },
      shenheData: {},      //核销详情对象
      receiveReconciliation: {},
      //核销明细应收
      reqViewDetailRecive: [],
      //核销明细收款
      reqViewDetailReciveOrder: [],
      // 表单校验
      rules: {
        documentDate: [
          { required: true, message: '请选择单据日期', trigger: 'change' }
        ],
        cusId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAllCus();
  },
  methods: {
    //审核
    shenhe(id) {
      this.shenheData = { ...this.receiveReconciliationList.find(item => item.id === id) };
      this.reviewDialogVisible = true;
      this.currentReviewId = id;
      this.reviewResult = '';
      this.reviewRemark = '';
    },
    //审核操作，调用后台
    submitReview() {
      if (this.reviewResult === 0) {
        this.$message.error('请选择审核结果');
        return;
      }
      this.approvalDto.id = this.currentReviewId;
      this.approvalDto.approvalResult = this.reviewResult;
      this.approvalDto.approvalRemark = this.reviewRemark;
      approval(this.approvalDto).then(response => {
        if (response.code === 200) {
          this.$message.success('审核成功');
          this.reviewDialogVisible = false;
          this.getList();
        }
      })
    },
    //获取所有客户
    getAllCus() {
      getAllCus().then(response => {
        this.cusList = response.data;
      });
    },
    // 处理应收单的选中
    handleSelectionChangeRecive(selection) {
      this.selectedRecives = selection; // 更新选中的应收单
    },
    // 处理核销明细-收款的选中
    handleSelectionChangeReciveOrderDetail(selection) {
      this.selectedReciveOrderDetails = selection; // 更新选中的核销明细
    },
    handleSelectionChangeReciveDetail(selection) {
      this.selectedReciveDetails = selection; // 更新选中的核销明细
    },
    // 处理收款单的选中
    handleSelectionChangeReciveOrder(selection) {
      this.selectedReciveOrders = selection; // 更新选中的收款单
    },
    // 添加应收单
    addMustRecive() {
      this.selectedRecives.forEach(recive => {
        const existingRecive = this.reciveDetailList.find(item =>
          item.sourceDocumentNo === recive.orderCode
        );
        if (!existingRecive) {
          this.reciveDetailList.push({
            id: recive.id,                        // 唯一标识
            sourceDocumentNo: recive.orderCode, // 源单号
            sourceDocumentType: recive.paymentType,
            typeName: '销售应收单',                        // 源单类型
            reqAmount: recive.money - recive.verMoney, // 未核销金额
            reconciliationAmount: 0,               // 初始核销金额
          });
        }
      });

      // 清空选中的应收单
      this.selectedRecives = [];
      this.$refs.reciveTable.clearSelection(); // 清空表格选中状态
    },
    // 添加收款单
    addRecive() {
      this.selectedReciveOrders.forEach(order => {
        const existingOrder = this.reciveOrderDetailList.find(item =>
          item.sourceDocumentNo === order.orderCode
        );
        if (!existingOrder) {
          this.reciveOrderDetailList.push({
            id: order.id,                         // 唯一标识
            sourceDocumentNo: order.orderCode,    // 源单号
            typeName: order.paymentTypeName,    // 源单类型名
            sourceDocumentType: order.paymentType,                  // 源单类型
            orderAmount: order.money - order.verMoney, // 未核销金额
            reconciliationAmount: 0,              // 初始核销金额
          });
        }
      });

      // 清空选中的收款单
      this.selectedReciveOrders = [];
      this.$refs.reciveOrderTable.clearSelection(); // 清空表格选中状态
    },
    // 更新收款合计
    updateReciveAll() {
      this.reciveOrderDetailList.forEach(item => {
        if (parseFloat(item.reconciliationAmount) > parseFloat(item.orderAmount)) {
          this.$message.error(`核销金额不能大于未核销金额，源单号: ${item.sourceDocumentNo}`);
          item.reconciliationAmount = item.orderAmount; // 恢复为未核销金额
        }
      });
      this.reciveAll = this.reciveOrderDetailList.reduce((total, item) => {
        return total + (parseFloat(item.reconciliationAmount) || 0); // 确保转换为数字
      }, 0);
    },

    // 移除收款的逻辑
    delRecive() {
      const selectedSourceDocs = this.selectedReciveOrderDetails.map(detail => detail.sourceDocumentNo);
      this.reciveOrderDetailList = this.reciveOrderDetailList.filter(item => !selectedSourceDocs.includes(item.sourceDocumentNo));
      this.updateReciveAll(); // 更新合计
    },

    //根据客户获取应收单和收款单列表列表
    cusSelectChanged() {
      this.reciveReq.customerId = this.formRecive.cusId;
      this.reciveOrder.customerId = this.formRecive.cusId;
      //调用对应的分页函数
      this.getReciveList();
      this.getReciveOrderList();
    },

    // 获取应收单列表
    getReciveList() {
      getReciveList(this.reciveReq).then(response => {
        this.reciveList = response.rows; // 更新应收单列表
        // 更新总条数，以便分页组件使用
        this.reciveReq.total = response.total;
      })
    },
    //获取收款单列表
    getReciveOrderList() {
      getReciveOrderList(this.reciveOrder).then(response => {
        this.reciveOrderList = response.rows; // 更新应收单列表
        // 更新总条数，以便分页组件使用
        this.reciveOrder.total = response.total;
      })
    },
    // 更新合计
    changeAmount() {
      this.reciveDetailList.forEach(item => {
        if (parseFloat(item.reconciliationAmount) > parseFloat(item.reqAmount)) {
          this.$message.error(`核销金额不能大于未核销金额，源单号: ${item.sourceDocumentNo}`);
          item.reconciliationAmount = item.reqAmount; // 恢复为未核销金额
        }
      });
      this.mustReciveAll = this.reciveDetailList.reduce((total, item) => {
        return total + (parseFloat(item.reconciliationAmount) || 0); // 确保转换为数字
      }, 0);
    },

    // 移除核销明细中的应收单
    delMustPay() {
      // 获取选中的源单号
      const selectedSourceDocs = this.selectedReciveDetails.map(detail => detail.sourceDocumentNo);
      this.reciveDetailList = this.reciveDetailList.filter(item => !selectedSourceDocs.includes(item.sourceDocumentNo));
      // 更新合计
      this.changeAmount();
    },

    /** 查询应收核销单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeModifyTime && '' != this.daterangeModifyTime) {
        this.queryParams.params["beginModifyTime"] = this.daterangeModifyTime[0];
        this.queryParams.params["endModifyTime"] = this.daterangeModifyTime[1];
      }
      listReceiveReconciliation(this.queryParams).then(response => {
        this.receiveReconciliationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.reciveOrderDetailList = [];
      this.reciveDetailList = [];
      this.formRecive = {};

      this.form = {
        id: null,
        documentDate: null,
        cusId: null,
        reconciliationAmount: null,
        documentStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        effectiveTime: null,
        approver: null,
        createBy: null,
        createTime: null,
        modifyBy: null,
        modifyTime: null,
        remark: null,
        approvalRemark: null,
        documentCode: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeModifyTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //查看核销单详情
    handleDetail(id) {
      this.receiveReconciliation = {};
      this.reqViewDetailRecive = [];
      this.reqViewDetailReciveOrder = [];
      getReceiveReconciliation(id).then(response => {
        this.receiveReconciliation = response.data;
        this.receiveReconciliation.receiveReconciliationDetailList.forEach(item => {
          if (item.sourceDocumentType === 101) {
            this.reqViewDetailReciveOrder.push(item);
          } else {
            this.reqViewDetailRecive.push(item);
          }
        });
      })
      console.log(this.receiveReconciliation.doucumentStage);
      this.view = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    close() {
      this.view = false;
      this.receiveReconciliation = {};
      this.reqViewDetailRecive = [];
      this.reqViewDetailReciveOrder = [];
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = false;
      this.title = "添加应收核销单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReceiveReconciliation(id).then(response => {
        this.formRecive = response.data;
        this.cusSelectChanged();
        this.open = true;
        this.isEdit = true;
        response.data.receiveReconciliationDetailList.forEach(item => {
          if (item.sourceDocumentType === 101) {
            this.reciveDetailList.push(item);
          } else {
            this.reciveOrderDetailList.push(item);
          }
        });
        this.changeAmount();
        this.updateReciveAll();
        this.title = "修改应收核销单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      //校验核销付款金额与应收金额是否一致
      if (this.reciveAll !== this.mustReciveAll || this.reciveAll === 0) {
        alert("核销付款金额与应收金额不一致，且金额不能为0,请核对后再提交！");
        return;
      }
      if (this.formRecive.documentDate == null) {
        alert("请选择单据日期！");
        return;
      }
      //正确添加逻辑
      this.formRecive.reconciliationAmount = this.reciveAll;
      // 过滤掉核销金额为0的明细
      const filteredReciveDetailList = this.reciveDetailList.filter(item => item.reconciliationAmount !== 0);
      const filteredReciveOrderDetailList = this.reciveOrderDetailList.filter(item => item.reconciliationAmount !== 0);

      // 合并两个过滤后的数组
      this.formRecive.receiveReconciliationDetailList = filteredReciveDetailList.concat(filteredReciveOrderDetailList);
      //判断是修改还是新增
      if (this.isEdit) {
        updateReceiveReconciliation(this.formRecive).then(res => {
          this.open = false;
          this.getList();
          this.$message.success("修改成功");
        })
      } else {
        addReceiveReconciliation(this.formRecive).then(res => {
          this.open = false;
          this.getList();
          this.$message.success("保存成功");
        })
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应收核销单编号为"' + ids + '"的数据项？').then(function () {
        return delReceiveReconciliation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('finance/receiveReconciliation/export', {
        ...this.queryParams
      }, `receiveReconciliation_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.my-content {
  color: #1890ff;
}

.custom-radio .el-radio__original {
  aria-hidden: false !important;
}
</style>
